package oakclub.utility;

import oakclub.global.Json;
import org.apache.http.client.HttpResponseException;
import org.apache.http.protocol.HTTP;

import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

public class HttpUtility
{
    public static final int REQUEST_TIMEOUT = 5000; // in miliseconds
    public static final boolean USE_CACHES = false;

    private static String buildUrlParams(Map<String, Object> params)
    {
        if(params == null || params.isEmpty())
        {
            return "";
        }

        String urlParams = "";
        for(Map.Entry<String, Object> entry : params.entrySet())
        {
            String key = entry.getKey();
            Object value = entry.getValue();

            if(urlParams.length() > 0)
            {
                urlParams += '&';
            }
            urlParams += key + '=' + value;
        }
        return urlParams;
    }

    public static String sendGet(String url, Map<String, Object> params) throws Exception
    {
        // build params
        String urlParams = buildUrlParams(params);
        if(urlParams.length() > 0)
        {
            url += '?' + urlParams;
        }

        // init connection
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("User-Agent", HTTP.USER_AGENT);
        connection.setConnectTimeout(REQUEST_TIMEOUT);
        connection.setReadTimeout(REQUEST_TIMEOUT);
        connection.setUseCaches(USE_CACHES);

        // check response code
        int responseCode = connection.getResponseCode();
        if(responseCode < 200 || 299 < responseCode)
        {
            throw new HttpResponseException(responseCode, "response code invalid");
        }

        // send & receive
        InputStream stream = connection.getInputStream();
        return StringUtility.getString(stream);
    }

    public static String sendPost(String url, Object params, String apiKey) throws Exception
    {
        // build params
        String jsonParams = "";
        if(params != null)
        {
            jsonParams = Json.getParser().toJson(params);
        }

        // init connection
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("User-Agent", HTTP.USER_AGENT);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Content-Length", String.valueOf(jsonParams.getBytes().length));
        connection.setConnectTimeout(REQUEST_TIMEOUT);
        connection.setReadTimeout(REQUEST_TIMEOUT);
        connection.setUseCaches(USE_CACHES);

        // add api key to header
        if(apiKey != null)
        {
            connection.setRequestProperty("Authorization", "key="+apiKey);
        }

        // set params
        connection.setDoOutput(true);
        DataOutputStream os = new DataOutputStream(connection.getOutputStream());
        os.writeBytes(jsonParams);
        os.flush();
        os.close();

        // check response code
        int responseCode = connection.getResponseCode();
        if(responseCode < 200 || 299 < responseCode)
        {
            throw new HttpResponseException(responseCode, "response code invalid");
        }

        // send & receive
        InputStream stream = connection.getInputStream();
        return StringUtility.getString(stream);
    }

    public static String sendPost(String url, Object params) throws Exception
    {
        return sendPost(url, params, null);
    }
}
